package com.tl.boot.common.utils;

import java.util.Base64;

/**
 * com.tl.boot.common.utils -- BytesUtil
 * Description:
 * Created by joshua_liu <a href="mailto:joshualwork@163.com"></a>
 * On 2019/9/11 9:32
 */
public class BytesUtil {
    /**
     * 二进制转十六进制字符串。每一个字节转为两位十六进制字符串。
     */
    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;

        for (int i = 0; i < b.length; i++) {
            stmp = Integer.toHexString(b[i] & 0XFF);

            if (stmp.length() == 1) {
                hs.append("0" + stmp);
            } else {
                hs.append(stmp);
            }
        }

        return hs.toString().toUpperCase();
    }

    /**
     * 十六进制转二进制
     *
     * @param hex
     * @return
     * @throws IllegalArgumentException
     */
    public static byte[] hex2byte(String hex) throws IllegalArgumentException {
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException();
        }

        if (hex.startsWith("0x")) {
            hex = hex.substring(2);
        }

        char[] arr = hex.toCharArray();
        byte[] b = new byte[hex.length() / 2];

        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
            String swap = "" + arr[i++] + arr[i];
            int byteint = Integer.parseInt(swap, 16) & 0xFF;
            b[j] = new Integer(byteint).byteValue();
        }

        return b;
    }

    public static String byte2base64(byte[] b) {
        return Base64.getEncoder().encodeToString(b);
    }

    public static byte[] base642byte(String src) {
        return Base64.getDecoder().decode(src);
    }
}

